package com.atguigu.controller;

import com.atguigu.dao.UserDao;
import com.atguigu.dao.impl.UserDaoImpl;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;
import com.atguigu.utils.MD5Util;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;

@WebServlet("/user/login")
public class UserLoginController extends HttpServlet {
    //根据页面提交数据判断是否登录成功

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //监测一下有没有其他ip访问
        System.out.println(req.getRemoteAddr());
        //拿到页面提交数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //根据页面提交数据进行判断，查找数据库中是否存在该用户名
        UserService userService = new UserServiceImpl();
        User user =  userService.findUserByName(username);
        if(user!=null){
            //若存在
            //若密码正确
            if(MD5Util.encrypt(password).equals(user.getPassword())){
                //将用户的登录信息作为cookie保存到客户端中
//                Cookie cookie1 = new Cookie("username",username);
//                Cookie cookie2 = new Cookie("password",password);
//                cookie1.setMaxAge(600);
//                cookie2.setMaxAge(600);
//                resp.addCookie(cookie1);
//                resp.addCookie(cookie2);
                //将信息存储到服务端
                HttpSession session = req.getSession();
                session.setAttribute("Session_User",user);
                resp.sendRedirect("/index.jsp");
            }
            //若密码不正确
            else{
                resp.sendRedirect("/loginPasswordError.html");
            }
        }
        else{
            //若不存在
            resp.sendRedirect("/loginUsernameError.html");
        }
    }
}
